<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.pw_id ? '编辑违禁词' : '添加违禁词'" v-model="visible" align-center width="700px"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <el-form-item label="词组" prop="word" :error="errorMsg"
        :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
        <div v-if="!form.pw_id" class="grid grid-cols-3 gap-x-3">
          <el-input v-model="form.word" :type="'textarea'" :autosize="{ minRows: 5, maxRows: 8 }" placeholder="请输入"
            class="col-span-2" @change="errorMsg = ''" />
          <div class="text-gray-500">一行为一个词组，多个词组请使用换行，最多一次添加200个。</div>
        </div>
        <el-input v-else v-model="form.word" placeholder="请输入" />
      </el-form-item>
      <div class="grid grid-cols-9 gap-x-3">
        <el-form-item label="风险等级" prop="level" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]"
          class="col-span-4">
          <VSelect v-model="form.level" :options="options.level" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="平台" prop="platform_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]"
          class="col-span-4">
          <VSelect v-model="form.platform_id" :options="options.platform" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="状态" class="col-span-1">
          <el-switch v-model="form.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value='1'
            :inactive-value='0' />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const success = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})
const errorMsg = ref('')

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  // 编辑
  if (id) {
    const res = await api.detail({ pw_id: id })
    form.value = res.data
    formRef?.value?.clearValidate()
  } else { //新增
    form.value = { status: 1 }
    formRef?.value?.resetFields()
  }
  loadings = reactive({})
  success.value = false
  errorMsg.value = ''
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}
// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  if (form.value.pw_id) {
    api.edit(form.value).then(res => {
      ElMessage.success('保存成功')
      success.value = true
      close()
    }).finally(() => {
      loadings.create = false
    })
  } else {
    form.value.word = form.value.word.split('\n').map(d => {
      if (/\*$/.test(d)) d = d.replace('*', '')
      return d
    }).join('\n')
    api.create(form.value).then(res => {
      const { code, data, message } = res
      if (code === 200) {
        ElMessage.success('保存成功')
        success.value = true
        close()
      } else {
        form.value.word = form.value.word.split('\n').map(d => {
          if (data.includes(d)) d += '*'
          return d
        }).join('\n')
        errorMsg.value = message
      }
    }).finally(() => {
      loadings.create = false
    })
  }
}

defineExpose({ open })
</script>